package com.itheima.filter;

import com.aliyuncs.utils.StringUtils;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        //获取请求路径
        String url = req.getRequestURI();
        //判断路径是否包含login
        if(url.contains("login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取token
        String token = req.getHeader("token");

        //判断token是否为空
        if(StringUtils.isEmpty(token)){
            //返回401
            res.setStatus(401);
            return;
        }

        //解析token
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            //返回401
            res.setStatus(401);
            return;
        }

        //放行
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
